package com.xy.job.admin.event

import com.xy.job.admin.domain.JobInstance
import com.xy.job.admin.domain.NotifyConfig
import com.xy.job.admin.domain.NotifyInstance
import com.xy.job.admin.enums.NotifyStatus
import com.xy.job.admin.repository.NotifyConfigRepository
import com.xy.job.admin.repository.NotifyInstanceRepository
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Component

@Component
class JobInstanceCompleteEventListener(
    var notifyConfigRepository: NotifyConfigRepository,
    var notifyInstanceRepository: NotifyInstanceRepository,
) {

    @EventListener(JobInstanceCompleteEvent::class)
    fun handleEvent(event: JobInstanceCompleteEvent) {
        val jobInstance = event.jobInstance
        if (jobInstance.notifyConfigId != null) {
            val notifyConfig = notifyConfigRepository.findById(jobInstance.notifyConfigId!!).orElseThrow()
            if (notifyConfig.enabled!!) {
                val notifyInstance = createNotifyInstance(jobInstance, notifyConfig)
                notifyInstanceRepository.save(notifyInstance)
            }
        }
    }

    fun createNotifyInstance(jobInstance: JobInstance, notifyConfig: NotifyConfig): NotifyInstance {
        return NotifyInstance().also {
            it.jobId = jobInstance.jobId
            it.jobInstanceId = jobInstance.id
            it.notifyConfigId = notifyConfig.id
            it.notifyChannelConfigId = notifyConfig.notifyChannelConfigId
            it.notifyScene = notifyConfig.notifyScene
            it.notifyStatus = NotifyStatus.WAIT
        }
    }
}